#include "stm32f10x.h"
#include "usart1.h"
#include "led.h"
#include "spi_enc28j60.h"
#include "web_server.h"
#include "misc.h"
#include "stm32f10x_tim.h"


NVIC_InitTypeDef NVIC_InitStructure;

void init_led(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);

    GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_12;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
}

float u=0, x=0;

float compute_u(float in)
{
  return  -1.3*in;
}

void TIM2_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM2,  TIM_IT_Update) == SET) {
        GPIOC->ODR ^= 0x00001000;
        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
        u = compute_u(x);
    }   
}

void init_timer(void) {
    /* Configure peripheral clock. */
    /* Let's leave PCLK1 at it's default setting of 36 MHz. */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    /* Time base configuration */
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_TimeBaseStructure.TIM_Period = 2000 -1 ; //zhc
    TIM_TimeBaseStructure.TIM_Prescaler = 72-1;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    // Enable the update interrupt
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

    /* Enable the timer IRQ in the NVIC module (so that the TIM2 interrupt
     * handler is enabled). */
    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    // Enable the timer
    TIM_Cmd(TIM2, ENABLE);
}


int main (void)
{

      SystemInit();

      init_led();
      init_timer();

      while(1);
}
